package bll

import (
	"github.com/hashicorp/golang-lru/v2/expirable"
	"io"
	infraOss "ota/lib/infra/oss"
	"time"
)

/* key 是 固件ID */
type firmwareCacheType struct {
	ossInstance *infraOss.Oss
	cache       *expirable.LRU[uint64, any]
}

/* 固件大小不是很大 */
func newFirmwareCache(ossInstance *infraOss.Oss, expire time.Duration) *firmwareCacheType {
	return &firmwareCacheType{
		ossInstance: ossInstance,
		cache:       expirable.NewLRU[uint64, any](16, nil, expire),
	}
}

func (a *firmwareCacheType) getSize(id uint64, filePath string) uint32 {
	return uint32(len(a.getBody(id, filePath)))
}

func (a *firmwareCacheType) getBody(id uint64, filePath string) []byte {
	v, ok := a.cache.Get(id)
	if ok {
		return v.([]byte)
	}

	s, _ := a.ossInstance.GetObjectStream(filePath)
	if s == nil {
		return nil
	}

	b, _ := io.ReadAll(s)
	if len(b) == 0 {
		return nil
	}
	go a.set(id, b)
	return b
}

func (a *firmwareCacheType) set(id uint64, b []byte) bool {

	return a.cache.Add(id, b)
}
